package com.henu.engineer.service

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.henu.engineer.dao.entity.cultivatingproject.*
import com.henu.engineer.dao.mapper.cultivatingproject.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * 师生共用的培养方案查看服务
 *
 * @author noexcept
 * @since 2021/8/10 23:06
 */
@Service
class CultivatingProjectService {

    @Autowired
    lateinit var cultivatingGoalXmlMapper: CultivatingGoalXmlMapper

    @Autowired
    lateinit var graduationRequirementXmlMapper: GraduationRequirementXmlMapper

    @Autowired
    lateinit var goalRequirementXmlMapper: GoalRequirementXmlMapper

    @Autowired
    lateinit var requirementIndicatorXmlMapper: RequirementIndicatorXmlMapper

    @Autowired
    lateinit var indicatorCourseXmlMapper: IndicatorCourseXmlMapper

    @Autowired
    lateinit var loginService: LoginService

    companion object {
        // TODO: 2021/8/11 下面两个值需要在第一次查询时成功后被赋值
        /**
         * 当前用户的有效毕业要求id
         */
        var graduationRequirementIds: List<String>? = null

        /**
         * 当前用户的有效指标点
         */
        var indicatorIds: List<Int>? = null
    }


    /**
     * 返回当前用户的对应专业和有效版本的培养目标
     * 这里的有效版本暂定为最新的版本（版本由date表示的）
     */
    fun getCultivatingGoalsBySpecAndVersion(): JSONObject {
        var specialization: String
        if (loginService.currentStudent != null)
            specialization = loginService.currentStudent?.specialization ?: ""
        else specialization = loginService.currentTeacher?.specialization ?: ""
        val res = JSONObject()
        res["count"] = 0;
        //查询该专业的最新版本
        val latestVersion = cultivatingGoalXmlMapper.selectLatestVersionInfoBySpec(specialization) ?: return res
        val list = cultivatingGoalXmlMapper.selectCultivatingGoalBySpecAndVersion(
            specialization,
            latestVersion
        )
        res["count"] = list.size
        res["data"] = list
        return res
    }

    /**
     * 返回当前用户（学生）的培养目标与支撑关系对
     *
     */
    fun getGoalRequirement(): List<GoalRequirement> {
        TODO()
    }

    /**
     * 获取当前用户的对应专业和有效版本的毕业要求
     * 这里的有效版本暂定为最新的版本（版本由date表示的）
     */
    fun getGraduationRequirementBySpecAndVersion(): JSONObject {
        var specialization: String
        if (loginService.currentStudent != null)
            specialization = loginService.currentStudent?.specialization ?: ""
        else specialization = loginService.currentTeacher?.specialization ?: ""
        val res = JSONObject()
        res["count"] = 0;
        //查询最新版本
        val latestVersion =
            graduationRequirementXmlMapper.selectLatestVersionBySpec(specialization) ?: return res
        //根据学生专业和最新版本号查询
        val list = graduationRequirementXmlMapper.selectBySpecAndVersion(specialization, latestVersion)
        //记录毕业要求id
        res["count"] = list.size
        graduationRequirementIds = list.map { it.id.toString() }
        res["data"] = list
        return res
    }

    /**
     * 返回当前用户的毕业要求需要的指标点，包括指标点内容
     * 每个毕业要求有多个指标点，通过毕业要求编号查询指标点
     */
    fun getRequirementIndicator(): JSONObject {
        if (graduationRequirementIds == null) {
            //填充毕业要求id
            getGraduationRequirementBySpecAndVersion()
        }
        val requirementIndicators =
            requirementIndicatorXmlMapper.selectIndicatorByRequirementIds(graduationRequirementIds!!)
        val res = JSONObject()
        val groupByRequirement = requirementIndicators.groupBy { it.requirementId }
        res["count"] = groupByRequirement.size
        val data = JSONArray()
        groupByRequirement.forEach { entry ->
            val singleRequirement = JSONObject()
            singleRequirement["count"] = entry.value.size
            singleRequirement["requirementId"] = entry.key
            val indicators = JSONArray()
            entry.value.forEach { it ->
                val singleIndicator = JSONObject()
                singleIndicator["indicatorId"] = it.indicatorId
                singleIndicator["content"] = it.content
                indicators.add(singleIndicator)
            }
            singleRequirement["indicators"] = indicators
            data.add(singleRequirement)
        }
        res["data"] = data
        //记录指标点id
        indicatorIds = requirementIndicators.map { it.indicatorId }.distinct()
        return res
    }

    /**
     * 返回毕业要求所需要的指标点的支撑课程及其支撑强度
     */
    fun getIndicatorCourse(): JSONObject {
        if (indicatorIds == null) {
            if (graduationRequirementIds == null) {
                //填充毕业要求id
                getGraduationRequirementBySpecAndVersion()
            }
            indicatorIds = requirementIndicatorXmlMapper.selectIndicatorByRequirementIds(graduationRequirementIds!!)
                .map { it.indicatorId }.distinct()
        }
        val res = JSONObject()
        val groupByIndicatorId =
            indicatorCourseXmlMapper.selectByIndicatorIds(indicatorIds!!).groupBy { it.indicatorId }
        res["count"] = groupByIndicatorId.size
        val data = JSONArray()
        groupByIndicatorId.forEach { entry ->
            val singleIndicator = JSONObject()
            singleIndicator["indicatorId"] = entry.key
            singleIndicator["count"] = entry.value.size

            val courses = JSONArray()
            entry.value.forEach {
                val singleCourse = JSONObject()
                singleCourse["courseId"] = it.courseSysId
                singleCourse["courseName"] = it.courseName
                singleCourse["intensity"] = it.intensity
                courses.add(singleCourse)
            }
            singleIndicator["courses"] = courses
            data.add(singleIndicator)
        }
        res["data"] = data
        return res
    }
}